<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>利用递归遍历数据</title>
  </head>
  <body>
    <script>
      const data = [
        {
          id: 1,
          name: "家电",
          goods: [
            {
              id: 11,
              gname: "冰箱",
              goods: [
                {
                  id: 111,
                  gname: "小米冰箱",
                },
              ],
            },
            {
              id: 12,
              gname: "冰箱",
            },
          ],
        },
        {
          id: 2,
          name: "服饰",
        },
      ]

      //需求: 输入id号, 就可以返回对应的数据对象
      // 1. 利用 forEach 去遍历里面的每一个对象
      getId = (json, id) => {
        let findObj = {}
        json.forEach((item, index) => {
          if (item.id == id) {
            findObj = item
            return item
          } else if (item.goods && item.goods.length > 0) {
            findObj = getId(item.goods, id)
          }
        })
        return findObj
      }
      const currentObj = getId(data, 111)
      console.log(currentObj)
    </script>
  </body>
</html>
